from PIL import Image, ImageDraw, ImageFont

def draw_grid(image, rows): 
# 打开图像

    # 获取图像的宽度和高度
    width, height = image.size

    print("width:", width, "height:", height)
    # 设置格子的数量
    cols = int(rows * width/height)

    # 计算每个格子的宽度和高度
    cell_width = width // cols
    cell_height = height // rows
    print("rows:", rows, "cols:", cols, "cell_width:", cell_width, "cell_height:", cell_height)

    # 创建一个可以在图像上绘制的对象
    draw = ImageDraw.Draw(image)

    # 绘制绿色细线
    for i in range(rows + 1):
        y = i * cell_height
        draw.line([(0, y), (width, y)], fill='green', width=1)

    for j in range(cols + 1):
        x = j * cell_width
        draw.line([(x, 0), (x, height)], fill='green', width=1)

    # 在每个格子的边界处添加文本标签
    font = ImageFont.load_default()  # 使用默认字体

    # 标注顶部和底部的列编号
    for col in range(cols):
        number = col
        x = col * cell_width + cell_width // 2
        top_text_pos = (x - 5, 0)  # 调整位置以居中显示
        draw.text(top_text_pos, str(number), fill='white', font=font)

    # 标注左侧和右侧的行编号
    for row in range(rows):
        number = row
        y = row * cell_height + cell_height // 2
        left_text_pos = (0, y - 5)  # 调整位置以居中显示
        draw.text(left_text_pos, str(number), fill='white', font=font)
    return cell_width, cell_height

def draw_click(image, click, cell_width, cell_height):
    x_center = (click[1] - 1) * cell_width + cell_width / 2
    y_center = (click[0] - 1) * cell_height + cell_height / 2
    print("x_center:", x_center, "y_center:", y_center)

    #在中心点绘制红点
    circle_radius = 5  # 圆的半径
    draw = ImageDraw.Draw(image)
    draw.ellipse(
        (
            x_center - circle_radius,
            y_center - circle_radius,
            x_center + circle_radius,
            y_center + circle_radius
        ),
        fill='red'
    )

if __name__ == '__main__':
    image_path = 'screenshot.png'  # 替换为你的图像路径
    image = Image.open(image_path)
    rows = 30
    w, h = draw_grid(image, rows)
    # 保存或显示图像
    draw_click(image, (10, 15), w, h)
    output_path = 'output_image.png'
    image.save(output_path)
    image.show()